package com.heima.comment.service.impl;

import com.heima.comment.service.CommentHotService;
import com.heima.model.comment.pojos.ApComment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @package com.heima.comment.service.impl
 * @Date 2022/3/10
 * @project heima-leadnews
 */
@Service
public class CommentHotServiceImpl implements CommentHotService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Async("taskExecutor")
    @Override
    public void hotCommentExecutor(ApComment apComment) {
        Query queryComment = Query.query(Criteria.where("id").is(apComment.getId()));
        List<ApComment> list=hostComment(apComment.getArticleId());
        if (list.size()>=5) {
            ApComment apCommentEnd = list.get(list.size() - 1);
            if (apCommentEnd.getLikes()<apComment.getLikes()+1){
                Query queryCommentEnd = Query.query(Criteria.where("id").is(apCommentEnd.getId()));
                Update update = new Update();
                update.set("flag", 0);
                mongoTemplate.updateMulti(queryCommentEnd, update, ApComment.class);
            }
        }else {
            Update update = new Update();
            update.set("flag",1);
            mongoTemplate.updateMulti(queryComment, update, ApComment.class);
        }
    }
    private List<ApComment> hostComment(Long articleId) {
        Query query = Query.query(Criteria.where("articleId").is(articleId).and("flag").is(1));
        Sort sort = Sort.by(Sort.Direction.DESC, "likes");
        query.with(sort);
        List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);
        return apComments;
    }
}
